import 'package:flutter/material.dart';
import 'package:fl_chart/fl_chart.dart';
import '../model/health_record.dart';
import '../service/database_service.dart';
import 'package:intl/intl.dart';

class TemperatureStats extends StatefulWidget {
  final String babyId;
  final DateTimeRange dateRange;

  const TemperatureStats({
    Key? key,
    required this.babyId,
    required this.dateRange,
  }) : super(key: key);

  @override
  _TemperatureStatsState createState() => _TemperatureStatsState();
}

class _TemperatureStatsState extends State<TemperatureStats> {
  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Padding(
        padding: EdgeInsets.all(16),
        child: Column(
          children: [
            _buildTemperatureChart(),
            SizedBox(height: 24),
            _buildTemperatureSummary(),
            SizedBox(height: 24),
            _buildTemperatureRecordsList(),
          ],
        ),
      ),
    );
  }

  Widget _buildTemperatureChart() {
    return Card(
      child: Padding(
        padding: EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('体温曲线', style: Theme.of(context).textTheme.titleLarge),
            SizedBox(height: 16),
            SizedBox(
              height: 200,
              child: FutureBuilder<List<HealthRecord>>(
                future: DatabaseService().getRecordsByType(
                  RecordType.temperature,
                  widget.babyId,
                  startDate: widget.dateRange.start,
                  endDate: widget.dateRange.end,
                ),
                builder: (context, snapshot) {
                  if (!snapshot.hasData) {
                    return Center(child: CircularProgressIndicator());
                  }

                  if (snapshot.data!.isEmpty) {
                    return Center(child: Text('暂无数据'));
                  }

                  final records = snapshot.data!;
                  records.sort((a, b) => a.timestamp.compareTo(b.timestamp));

                  return LineChart(
                    LineChartData(
                      lineBarsData: [
                        LineChartBarData(
                          spots:
                              records.map((record) {
                                return FlSpot(
                                  record.timestamp.millisecondsSinceEpoch
                                      .toDouble(),
                                  record.data['temperature'] as double,
                                );
                              }).toList(),
                          isCurved: true,
                          color: Colors.red,
                          dotData: FlDotData(show: true),
                        ),
                      ],
                      gridData: FlGridData(
                        getDrawingHorizontalLine: (value) {
                          return FlLine(
                            color:
                                value == 37.3
                                    ? Colors.red.withOpacity(0.3)
                                    : Colors.grey.shade200,
                            strokeWidth: value == 37.3 ? 2 : 1,
                          );
                        },
                      ),
                      titlesData: FlTitlesData(
                        bottomTitles: AxisTitles(
                          sideTitles: SideTitles(
                            showTitles: true,
                            getTitlesWidget: (value, meta) {
                              final date = DateTime.fromMillisecondsSinceEpoch(
                                value.toInt(),
                              );
                              return Padding(
                                padding: EdgeInsets.only(top: 8.0),
                                child: Text(
                                  DateFormat('MM/dd HH:mm').format(date),
                                  style: TextStyle(fontSize: 10),
                                ),
                              );
                            },
                          ),
                        ),
                        leftTitles: AxisTitles(
                          sideTitles: SideTitles(
                            showTitles: true,
                            getTitlesWidget: (value, meta) {
                              return Text('${value.toStringAsFixed(1)}°C');
                            },
                            interval: 0.5,
                          ),
                        ),
                      ),
                      minY: 35,
                      maxY: 42,
                    ),
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildTemperatureSummary() {
    return FutureBuilder<List<HealthRecord>>(
      future: DatabaseService().getRecordsByType(
        RecordType.temperature,
        widget.babyId,
        startDate: widget.dateRange.start,
        endDate: widget.dateRange.end,
      ),
      builder: (context, snapshot) {
        if (!snapshot.hasData || snapshot.data!.isEmpty) {
          return SizedBox.shrink();
        }

        final records = snapshot.data!;
        final temperatures =
            records.map((r) => r.data['temperature'] as double).toList();
        final maxTemp = temperatures.reduce(
          (max, temp) => temp > max ? temp : max,
        );
        final minTemp = temperatures.reduce(
          (min, temp) => temp < min ? temp : min,
        );
        final avgTemp =
            temperatures.reduce((a, b) => a + b) / temperatures.length;

        return Card(
          child: Padding(
            padding: EdgeInsets.all(16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text('体温统计', style: Theme.of(context).textTheme.titleLarge),
                SizedBox(height: 16),
                _buildSummaryRow('最高温度', '${maxTemp.toStringAsFixed(1)}°C'),
                _buildSummaryRow('最低温度', '${minTemp.toStringAsFixed(1)}°C'),
                _buildSummaryRow('平均温度', '${avgTemp.toStringAsFixed(1)}°C'),
                _buildSummaryRow('记录次数', '${records.length}次'),
              ],
            ),
          ),
        );
      },
    );
  }

  Widget _buildSummaryRow(String label, String value) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 4),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(label),
          Text(value, style: TextStyle(fontWeight: FontWeight.bold)),
        ],
      ),
    );
  }

  Widget _buildTemperatureRecordsList() {
    return Card(
      child: FutureBuilder<List<HealthRecord>>(
        future: DatabaseService().getRecordsByType(
          RecordType.temperature,
          widget.babyId,
          startDate: widget.dateRange.start,
          endDate: widget.dateRange.end,
        ),
        builder: (context, snapshot) {
          if (!snapshot.hasData) {
            return Center(child: CircularProgressIndicator());
          }

          final records = snapshot.data!;
          records.sort((a, b) => b.timestamp.compareTo(a.timestamp));

          return ListView.builder(
            shrinkWrap: true,
            physics: NeverScrollableScrollPhysics(),
            itemCount: records.length,
            itemBuilder: (context, index) {
              final record = records[index];
              final temp = record.data['temperature'] as double;
              final isHighTemp = temp >= 37.3;

              return ListTile(
                title: Text(
                  '${temp.toStringAsFixed(1)}°C',
                  style: TextStyle(
                    color: isHighTemp ? Colors.red : null,
                    fontWeight: isHighTemp ? FontWeight.bold : null,
                  ),
                ),
                subtitle: Text(
                  DateFormat('yyyy-MM-dd HH:mm').format(record.timestamp),
                ),
                trailing: Text(record.data['notes'] ?? ''),
              );
            },
          );
        },
      ),
    );
  }
}
